<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="物料名称" prop="materialName">
            <el-input
              v-model="baTable.form.items!.materialName"
              placeholder="请输入物料名称"
            />
          </el-form-item>
          <el-form-item label="物料编号" prop="materialCode">
            <el-input
              v-model="baTable.form.items!.materialCode"
              placeholder="请输入物料编号"
            />
          </el-form-item>
          <FormItem
            label="物料类型"
            v-model="baTable.form.items!.materialType"
            type="radio"
            prop="materialType"
            :data="{
              content: {
                成品: '成品',
                自制件: '自制件',
                采购件: '采购件',
                原料: '原料',
              },
              childrenAttr: { border: true },
            }"
          />
          <el-form-item label="采购数量" prop="purchaseQuantity">
            <el-input-number
              v-model="baTable.form.items!.purchaseQuantity"
              :max="purchase.purchaseMaterialInfo.maxStock"
              @blur="getSumPrice"
            />
          </el-form-item>
          <el-form-item prop="unit" label="单位">
            <el-input
              v-model="baTable.form.items!.unit"
              placeholder="请输入单位"
            ></el-input>
          </el-form-item>
          <el-form-item label="供应商列表">
            <el-input
              v-model="filterText"
              placeholder="输入关键字进行过滤"
            />
            <el-scrollbar
              ref="verticalMenusRef"
              class="vertical-menus-scrollbar"
              style="height: 150px"
            >
              <el-tree
                ref="treeRef"
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.supplierId]
                    : []
                "
                class="tree-border"
                :data="state.supplierOptions"
                :props="defaultProps"
                node-key="supplierId"
                show-checkbox
                @check="handleCheckChange"
                :filter-node-method="filterNode"
              />
            </el-scrollbar>
          </el-form-item>
          <el-form-item label="含税单价">
            <el-input-number v-model="baTable.form.items!.taxUnitPrice" />
          </el-form-item>
          <el-form-item label="未含税单价" prop="unitPriceWithoutTax">
            <el-input
              v-model="baTable.form.items!.unitPriceWithoutTax"
              placeholder="请输入未含税单价"
            />
          </el-form-item>
          <el-form-item label="采购数量">
            <el-input-number
              v-model="baTable.form.items!.purchaseQuantity"
              :max="purchase.purchaseMaterialInfo.maxStock"
              @change="getSumPrice"
            />
            <div class="block-help">选择采购数量计算总价</div>
          </el-form-item>
          <el-form-item label="含税总价">
            <el-input-number v-model="baTable.form.items!.taxTotalPrice" />
          </el-form-item>
          <el-form-item label="未含税总价" prop="totalPriceWithoutTax">
            <el-input
              v-model="baTable.form.items!.totalPriceWithoutTax"
              placeholder="请输入未含税总价"
            />
          </el-form-item>
          <el-form-item label="结算方式" prop="settlementMethod">
            <el-tree-select
              v-model="baTable.form.items!.settlementMethod"
              :data="state.purchaseSettlementOptions"
              check-strictly
              :props="{
                label: 'dictLabel',
                value: 'dictValue',
                children: 'children',
              }"
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item label="开票方式" prop="billingMethod">
            <el-tree-select
              v-model="baTable.form.items!.billingMethod"
              :data="state.purchaseBillingOptions"
              check-strictly
              :props="{
                label: 'dictLabel',
                value: 'dictValue',
                children: 'children',
              }"
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item label="申购人姓名" prop="applicantName">
            <el-input v-model="baTable.form.items!.applicantName" />
          </el-form-item>
          <el-form-item label="采购人" prop="purchaserName">
            <el-select
              v-model="baTable.form.items!.purchaserName"
              placeholder="请选择采购人"
              @change="personChange"
              value-key="userId"
            >
              <el-option
                v-for="item in state.UserDeptOptions"
                :key="item.userId"
                :label="item.nickName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          {{ baTable.form.operate === "itemAdd" ? "确定并新增下一项" : "确定" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, inject, onMounted, watch } from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormItemRule, FormRules, ElTree } from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { getDictData } from "@/utils/common";

const formRef = ref<InstanceType<typeof ElForm>>();
const baTable = inject("baTable") as baTableClass;
const bom = inject("bom") as any;
const purchase = inject("purchase") as any;
const dictionary = inject("dictionary") as any;
const User = inject("User") as any;
const supplier = inject("supplier") as any;
const adminInfo = inject("adminInfo") as any;
const chain = inject("chain") as any;
const filterText = ref(""); //供应商列表关键词过滤
const treeRef = ref<InstanceType<typeof ElTree>>();

const state: {
  typeOptions: any;
  stationOptions: any;
  processOptions: anyObj[];
  purchaseSettlementOptions: anyObj[];
  purchaseBillingOptions: anyObj[];
  UserDeptOptions: anyObj[];
  supplierOptions: anyObj[];
  processIds: any;
} = reactive({
  typeOptions: [], //物料类型列表
  stationOptions: [], //工作中心列表
  processOptions: [], //工序列表
  purchaseSettlementOptions: [], //结算方式列表
  purchaseBillingOptions: [], //开票方式列表
  UserDeptOptions: [], //人员班组列表
  supplierOptions: [], //供应商列表
  processIds: 0,
});

const defaultProps = {
  children: "children",
  label: "supplierName",
  value: "supplierId",
};

// 关键词过滤
const filterNode = (value: string, data: any) => {
  console.log("关键词过滤", data);

  if (!value) return true;
  return data.supplierName.includes(value);
};
const handleCheckChange = (row: any, node: any) => {
  console.log("row", row, "node", node);
  if (node.checkedKeys.length == 0) {
    baTable.form.items!.taxUnitPrice = ""; //获取含税单价以及未含税单价
    baTable.form.items!.unitPriceWithoutTax = "";
  } else {
    //!获取供应商下相关供应链情况数据
    getSupplierChain(row, node);
  }
};
//获取供应商下相关供应链情况数据
const getSupplierChain = (row: any, node: any) => {
  chain
    .getChain({
      supplierName: row.supplierName,
      materialName: baTable.form.items!.materialName,
    })
    .then((res: any) => {
      console.log("获取供应商下相关供应链情况数据", res);
      baTable.form.items!.taxUnitPrice = res.rows[0].taxUnitPrice; //获取含税单价以及未含税单价
      baTable.form.items!.unitPriceWithoutTax = res.rows[0].unitPriceWithoutTax;
    });
};

const rules = reactive<FormRules>({
  materialName: [
    { required: true, message: "物料名称不能为空", trigger: "blur" },
  ],
  materialCode: [
    { required: true, message: "物料编码不能为空", trigger: "blur" },
  ],
  purchaseQuantity: [
    { required: true, message: "采购数量不能为空", trigger: "blur" },
  ],
  unit: [{ required: true, message: "单位不能为空", trigger: "blur" }],
  process: [{ required: true, message: "工序号不能为空", trigger: "blur" }],
  processName: [
    { required: true, message: "工序名称不能为空", trigger: "blur" },
  ],
  prepareTime: [
    { required: true, message: "准备时间不能为空", trigger: "blur" },
  ],
  equipmentName: [
    { required: true, message: "设备名称不能为空", trigger: "blur" },
  ],
  productTime: [
    { required: true, message: "加工时间不能为空", trigger: "blur" },
  ],
  afterTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
  type: [{ required: true, message: "工序类型不能为空", trigger: "blur" }],
  //   perUsage: [{ required: true, message: "每用量不能为空", trigger: "blur" }],
  applicantName: [
    { required: true, message: "申购人不能为空", trigger: "blur" },
  ],
  materialType: [
    { required: true, message: "物料类型不能为空", trigger: "blur" },
  ],
});

//获取结算方式/开票方式字典
const getMenuStatus = () => {
  //采购单结算方式
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["settlementMethod"])
  ) {
    dictionary.getDictInfo("sys_purchase_settlement").then((res: any) => {
      dictionary.moreTags["settlementMethod"] = getDictData(res);
      dictionary.moreTags["settlementMethodOrigin"] = res;
    });
  } else {
    state.purchaseSettlementOptions =
      dictionary.moreTags["settlementMethodOrigin"];
  }
  //开票方式
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["billingMethod"])
  ) {
    dictionary.getDictInfo("sys_purchase_billing").then((res: any) => {
      dictionary.moreTags["billingMethod"] = getDictData(res);
      dictionary.moreTags["billingMethodOrigin"] = res;
    });
  } else {
    state.purchaseBillingOptions = dictionary.moreTags["billingMethodOrigin"];
  }
};
//获取结算方式/开票方式字典
getMenuStatus();

//计算两个总价
const getSumPrice = () => {
  //含税总价
  baTable.form.items!.taxTotalPrice =
    baTable.form.items!.purchaseQuantity * baTable.form.items!.taxUnitPrice;
  //不含税总价
  baTable.form.items!.totalPriceWithoutTax =
    baTable.form.items!.purchaseQuantity *
    baTable.form.items!.unitPriceWithoutTax;
};

//采购人员
const personChange = (val: any) => {
  console.log("采购人员", val);
  baTable.form.items!.purchaserName = val.nickName; //采购人员名称
  baTable.form.items!.purchaserId = val.userId; //采购人员id
};

onMounted(() => {
  //获取人员(采购)
  User.getUsers({
    pageSize: 10000,
  }).then((res: any) => {
    state.UserDeptOptions = res.rows;
  });
  //获取供应商列表数据
  supplier.getSupplier().then((res: any) => {
    state.supplierOptions = res.rows;
  });

  setTimeout(() => {
    baTable.form.items!.materialName = purchase.purchaseMaterialInfo.name; //物料名称
    baTable.form.items!.materialCode = purchase.purchaseMaterialInfo.code; //物料编号
    baTable.form.items!.materialType = purchase.purchaseMaterialInfo.type; //物料型号
    baTable.form.items!.unit = purchase.purchaseMaterialInfo.unit; //单位
    baTable.form.items!.applicantName = adminInfo.nickName; //申购人姓名
    baTable.form.items!.applicantId = adminInfo.userId; //申购人ID
    baTable.form.items!.purchaserName = adminInfo.nickName; //申购人ID
    baTable.form.items!.purchaserId = adminInfo.userId; //申购人ID
  });
});

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;
  width: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
.vertical-menus-scrollbar {
  border: 1px solid #e5e6e7;
}
.tree-border {
  width: 100%;
  margin-top: 5px;
  border-radius: 4px;
}
</style>
